
import pandas as  pd
import numpy as  np
# import stats as stats
from scipy import stats


pdt=pd.read_csv('ab_data.csv');
print(pdt)

# 根据常规默认值确定α ,β,K 值 α = 0.05, β = 0.2 ,K = 1 (组件样本均衡)

alpha = 0.05
beta = 0.2
k =1

z_alpha = stats.norm.ppf(1-alpha)
z_beta = stats.norm.ppf(1-beta)
print(z_alpha,z_beta)

#求对照组的点击率

pa=pdt[(pdt.group=='control')&(pdt.landing_page=='old_page')]['converted'].mean();

print(pa)
#我们定义了β=0.2，
##H1 为实验组点击率 Pb-对照组点击率 Pb > 0,为计算样本量，
# 我们指定一个非 0 的值，此值绝对值越小样本量越大
# pb-pa>0.02
pb=pa+0.02
pa_b=pa-pb;
print(pa_b)
#nb=((pa(1-pa))+pb(1-pb))(z1-z1)/(pa-pb)
n=(pa*(1-pa)+pb*(1-pb))*((z_alpha+z_beta)/(pa_b))**2
# n=3501.977116767441
print(n)
#查寻样本量是否符合要求
p_count=pdt.groupby(['group','landing_page']).count();
print(p_count)
# = (pa*p1_a+pb*p1_b)*(z1_alpha+z1_beta)**2/(pa_b**2)
#yangbenlang= = (pa*p1_a+pb*p1_b)*(z1_alpha+z1_beta)**2/(pa_b**2)
#样本量14W多符合要求

pdt['riqi']=pdt.timestamp.str[0:10]
print((pdt.timestamp).dtype)
print(pdt)
#抽取一天的数据
pts=pdt[pdt.riqi=='2017-01-11']

# print(pts)
# 计算统计量

p1=pts[(pts.group=='control')&(pts.landing_page=='old_page')]['converted'].mean();

p2=pts[(pts.group=='treatment')&(pts.landing_page=='new_page')]['converted'].mean();
print('------------计算P1,P2')
print(p1,p2)
print('------------计算样本量n1,n2')
n1=pts[(pts.group=='treatment')&(pts.landing_page=='new_page')]['user_id'].count();
n2=pts[(pts.group=='control')&(pts.landing_page=='old_page')]['user_id'].count();
print(n1,n2)

#sigma = np.sqrt((p1*(1-p1)/n1)+(p2*(1-p2)/n2))
#求方差
sigma=np.sqrt(((p1*(1-p1))/n1)+(p2*(1-p2)/n2))
print('----------求方差')
print(sigma)
print('----------求P值')
#求P值
p=1-stats.norm.cdf((p2-p1),0,sigma)

print(p)

if(p>alpha):
    print('显著性p>alpha，实验组的点击率<控制组的点击率，不显著')
else:
    print('显著性p<alpha，实验组的点击率>控制组的点击率，显著')


def AbTest(df:pd.DataFrame,alpht=0.5,group_col:str=None,value_col:str=None):
    ''' :param df: 被分析 DateFrame 对象
    :param alpha: 临界值
    :param group_col: 组列的名字，默认为 df 的第一列
    :param value_col: 值列的名字,默认为 df 的第 2 列
    :return:tongjiliang,p_value,p_conclusion (统计量，p 值，检验结论)
    '''

    if not group_col:
        group_col=df.columns[0]
    if not value_col:
        value_col=df.columns[1]
    #求点击率
    tem_p=df.groupby(group_col,as_index=False)[value_col].mean();
    #求点击量
    tem_count=df.groupby(group_col,as_index=False)[value_col].count()
    #
    tempa_b=tem_p.iloc[1,1]-tem_p.iloc[0,1]
    #求方差
    sigma2 = np.sqrt(((tem_p.iloc[0,1] * (1 - tem_p.iloc[0,1])) / tem_count.iloc[0,1]) +
                     ( (tem_p.iloc[1,1] * (1 - tem_p.iloc[1,1])) / tem_count.iloc[1,1]))
    # 求P值
    p_value=1 - stats.norm.cdf(tempa_b, 0, sigma2)

    print(p_value)
    if p_value<alpha:
        result='显著'
    else:
        result='不显著'
    tem_test=[tem_p.iloc[0,1],tem_p.iloc[1,1],tempa_b,sigma2,p_value,result]

    tem_return=pd.DataFrame([tem_test],columns=['PA','PB','统计量','方差','P值','显著性']);

    return tem_return

data=pts[pts.riqi=='2017-01-11'].loc[(pts.group=='control')&(pts.landing_page=='old_page')
                                     |(pts.group=='treatment')&(pts.landing_page=='new_page'),['group','converted']]
# print(data)

print(AbTest(data))


